/*  -*- mode: c++; coding: utf-8; c-file-style: "stroustrup"; -*-

    Copyright 2008 Asier Aguirre <asier.aguirre@gmail.com>
    This file is part of Intromit.

    Intromit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Intromit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Intromit.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef FILE_MNG_HH
#define FILE_MNG_HH
//! \addtogroup util
//@{

// INCLUDES
#include <stdio.h>
#include <stdlib.h>

// DEFINES
#define FILE_INIT        2048
#define FILE_TAM_BUFFER  2048
#define FILE_INC_ITEMS  16384

class file_mng
{
    // ** CTOR/INIT VARIABLES **

    // ** STATUS VARIABLES **

    // ** PRIVATE FUNCTIONS **

    // internal
    void ctor();
    void dtor();

public:
    file_mng();
    ~file_mng();

    // returns whether file is regular (NOTE: _nf stands for no_format)
    static bool regular(const char *format, ...);
    static bool regular_nf(const char *filename);

    // returns whether file is directory
    static bool directory(const char *format, ...);

    // search an empty slot in directory: example hole("/tmp/kk%04d", ".%s", "extension");
    static int hole(int start, const char *init_format_number, const char *end_format, ...);
    static int hole_nf(int start, const char *init_format_number, const char *end_filename);

    // load
    template<typename T> static int load_n_max_nf(T *&vector, int &n, int &max, const char *filename)
    {
	FILE *arch;
	if((arch=fopen(filename, "r")))
	{
	    char *buffer[FILE_TAM_BUFFER*sizeof(T)];
	    int n_buffer;
	    n=0;
	    char *items=(char*)vector;
	    while((n_buffer=fread(buffer, sizeof(T), FILE_TAM_BUFFER, arch))>0)
	    {
		int i=n;
		n+=n_buffer;
		if(n>max)
		{
		    max+=FILE_INC_ITEMS;
		    items=(char*)realloc(items, max*sizeof(T));
		}
		memcpy(&items[i*sizeof(T)], buffer, n_buffer*sizeof(T));
	    }
	    fclose(arch);

	    // restore some memory
	    if(max>n*2 || max>n+(1<<16))
	    {
		max=n;
		items=(char*)realloc(items, max*sizeof(T));
	    }

	    // save in real variables
	    vector=(T*)items;
	    return 1;
	}
	return 0;
    }

    // delete
    static bool del(const char *format, ...);
    static bool del_nf(const char *filename);
};

//@}
#endif

/* Offline metadata attributes:

   @metadata_attrs(
	file_mng:
					~select
   )
*/
